/*
 * 文件：    pub-jquery.js
 * 说明：    公共函数库，jQuery 兼容
 * version:  0.1
 * Author:   MDZ <mdztiger@gmail.com>
 */

/* Javascript 原型的一些方法 */
// 去除两边空格
String.prototype.Trim = function()
{
   return this.replace(/(^\s*)|(\s*$)/g, "");
}
// 去除左边空格
String.prototype.LTrim = function()
{
   return this.replace(/(^\s*)/g, "");
}
// 去除右边空格
String.prototype.RTrim = function()
{
   return this.replace(/(\s*$)/g, "");
}
// 去除所有空格
String.prototype.ATrim = function()
{
   return this.replace(/\s/g, "");
}
// 从己经转义的字符串中恢复
String.prototype.unescapeString = function()
{
	var a = /\\\'/g;          //' 转义
	return this.replace(/\\\"/g, "\"").replace(a, "\'").replace(/\\\\/g, "\\");
}

/* 生成 Select 表单项 */
function makeSelectOption(optionHash, selectedOption)
{
   var str = "";
   $.each(optionHash, function(k, v){
	  str += "<option value=\"" + k + "\" ";
	  str += (selectedOption == k) ? " selected=\"selected\" " : "";
	  str += ">" + v + "</option>\n";
   });
   return str;
}

/* 生成带值的表单项 */
function makeSelectOptionWithValue(optionHash, selectedOption)
{
   var str = "";
   $.each(optionHash, function(k, v){
	  str += "<option value=\"" + k + "\" ";
	  str += (selectedOption == k) ? " selected=\"selected\" " : "";
	  str += ">" + k + ":" + v + "</option>\n";
   });
   return str;
}

// 美化表格
function tablePretty(handler)
{
   $(handler).find("tr:odd").addClass("even")
	 .hover(function(){
		$(this).addClass("evenHover");
	 }, function(){
		$(this).removeClass("evenHover");
	 }).end()
	   .find("tr:even").addClass("odd")
		 .hover(function(){
			$(this).addClass("oddHover");
		 }, function(){
			$(this).removeClass("oddHover");
		 });
}

// 分页类
var Pager = function(total, page_span, obj_name, do_fun, start_page)
{
   this.total = total;
   this.page_span = page_span;
   this.obj_name = obj_name;
   this.do_fun = do_fun;
   this.chPage(start_page);
}
Pager.prototype = 
{
   // 更新数据总条数
   chTotal: function(total) {
	  this.total = total;
   },
   // 更新 Page 条
   chPage: function(page) {
	  eval((this.do_fun + "(" + page + ");"));
	  this.showPage(page);
   },
   // 显示 Page 条
   showPage: function(page) {
	  var str = "";
	  var options = {};
	  for (var i = 1; i <= this.total; i ++)
		{
		   options[i] = (i + "/" + this.total);
		}
	  str += " | ";
	  str += (page == 1) ? " 首页 " : " <a href=\"javascript:void(0);\" onclick=\"" + this.obj_name + ".chPage(1);\">首页</a> ";
	  str += " | ";
	  str += (page == 1) ? " 上一页 " : " <a href=\"javascript:void(0);\" onclick=\"" + this.obj_name + ".chPage(" + (parseInt(page, 10) - 1) + ");\">上一页</a> ";
	  str += " | ";
	  str += (page == this.total) ? " 下一页 " : " <a href=\"javascript:void(0);\" onclick=\"" + this.obj_name + ".chPage(" + (parseInt(page, 10) + 1) + ");\">下一页</a> ";
	  str += " | ";
	  str += (page == this.total) ? " 末页 " : " <a href=\"javascript:void(0);\" onclick=\"" + this.obj_name + ".chPage(" + this.total + ");\">末页</a> ";
	  str += " | ";
	  str += "&nbsp; &nbsp;";
	  str += " 页码： ";
	  str += "<select onchange=\"" + this.obj_name + ".chPage(this.value);\">";
	  str += makeSelectOption(options, page);
	  str += "</select>";
	  $(this.page_span).html(str);
   }   
}

/* ----------------------------------------- */
/* ----- 获取公司、部门、职位列表 ----- */
/* 获取公司 */
function getCompanyList(update_id, url, selected)
{
   var up_block = $(update_id);
   $.get(url, function(xmlobj){
	  up_block.html("").append($("<option></option>").val("-1").html("请选择公司..."));
	  $(xmlobj).find("company").each(function(i){
		 var item_id = $(this).attr("id");
		 var item_name = $(this).attr("name");
		 var item_power = $(this).attr("power");
		 up_block.append($("<option></option>").val(item_id).attr("power", item_power).html(item_name));
	  });
	  up_block.find("option[@value='" + selected + "']").attr("selected", "selected");
   });
}
/* 获取部门 */
function getSectionList(update_id, url, v, selected)
{
   var up_block = $(update_id);
   $.get(url, function(xmlobj){
	  up_block.html("").append($("<option></option>").val("-1").html("请选择部门..."));
	  $(xmlobj).find("company[@id='" + v + "']")
		.find("section")
		  .each(function(){
			 var item_id = $(this).attr("id");
			 var item_name = $(this).attr("name");
			 var item_power = $(this).attr("power");
			 var item_masterid = $(this).attr("masterid");
			 up_block.append($("<option></option>").val(item_id).attr("power", item_power).attr("masterid", item_masterid).html(item_name));
		  });
	  up_block.find("option[@value='" + selected + "']").attr("selected", "selected");;
   });
}
/* 获取职位 */
function getPositionList(update_id, url, v, selected)
{
   var up_block = $(update_id);
   $.get(url, function(xmlobj){
	  up_block.html("").append($("<option></option>").val("-1").html("请选择职位..."));
	  $(xmlobj).find("section[@id='" + v + "']")
		.find("position")
		  .each(function(){
			 var item_id = $(this).attr("id");
			 var item_name = $(this).attr("name");
			 var item_power = $(this).attr("power");
			 up_block.append($("<option></option>").val(item_id).attr("power", item_power).html(item_name));
		  });
	  up_block.find("option[@value='" + selected + "']").attr("selected", "selected");;
   });
}
/* 获取用户列表，通过某一类型（公司？部门？职位？办公室？组？） */
function getUserList(update_id, url, t, v, selected, except)
{
   // t 值 ── "c":company, "s":section, "p":position, "o":office, "g":group
   var up_block = $(update_id);
   var pars = { "by": t, "bv": v };
   $.get(url, pars, function(xmlobj){
	  up_block.html("").append($("<option></option>").val("-1").html("请选择人员..."));
	  $(xmlobj).find("user").not("[@id='" + except + "']")
		  .each(function(){
			 var item_id = $(this).attr("id");
			 var item_name = $(this).attr("name");
			 up_block.append($("<option></option>").val(item_id).html(item_name));
		  });
	  up_block.find("option[@value='" + selected + "']").attr("selected", "selected");;
   });
}

/* -------- 通过 js 获取公司列表 --------- */
function getCompanyListViaJs(update_id, selected)
{
	var up_block = $(update_id);
	up_block.html("").append($("<option></option>").val("-1").html("请选择公司..."));
	if (typeof(__company_2_position__) != 'undefined')
	{
		$.each(__company_2_position__, function(i, n) {
			up_block.append($("<option></option>").val(i).attr("power", n[2]).html(n[1]));
		});
	}
	up_block.find("option[@value='" + selected + "']").attr("selected", "selected");
}
/* ---------- 通过 js 获取公司列表按钮 ---------- */
function getCompanyButtonsViaJs(update_id)
{
	var up_block = $(update_id);
	up_block.html("");
	if (typeof(__company_2_position__) != 'undefined')
	{
		$.each(__company_2_position__, function(i, n) {
			up_block.append($("<input type=\"button\" />").attr("cid", i).attr("power", n[2]).val(n[1]));
		});
	}
}
/* --------- 通过 js 获取部门列表 --------- */
function getSectionListViaJs(update_id, v, selected)
{
	var up_block = $(update_id);
	up_block.html("").append($("<option></option>").val("-1").html("请选择部门..."));
	if (typeof(__company_2_position__[v]) != 'undefined')
	{
		$.each(__company_2_position__[v][0], function(i, n) {
			up_block.append($("<option></option>").val(i).attr("power", n[2]).attr("masterid", n[3]).html(n[1]));
		});
	}
	up_block.find("option[@value='" + selected + "']").attr("selected", "selected");
}
/* --------- 通过 js 获取部门列表按钮 --------- */
function getSectionButtonsViaJs(update_id, v)
{
	var up_block = $(update_id);
	up_block.html("");
	if (typeof(__company_2_position__[v]) != 'undefined')
	{
		$.each(__company_2_position__[v][0], function(i, n) {
			up_block.append($("<input type=\"button\" />").attr("sid", i).attr("power", n[2]).attr("masterid", n[3]).val(n[1]));
		});
	}
}
/* ---------- 通过 js 获取职位列表 ----------- */
function getPositionListViaJs(update_id, v, selected)
{
	var up_block = $(update_id);
	var a;
	up_block.html("").append($("<option></option>").val("-1").html("请选择职位..."));
	if (typeof(__company_2_position__) != 'undefined')
	{
		$.each(__company_2_position__, function(i, n) {
			if (typeof(__company_2_position__[i][0][v]) != 'undefined') { a = __company_2_position__[i][0][v]; }
		});
	}
	if (typeof(a) != 'undefined')
	{
		$.each(a[0], function(i, n) {
			up_block.append($("<option></option>").val(i).attr("power", n[1]).html(n[0]));
		});
	}
	up_block.find("option[@value='" + selected + "']").attr("selected", "selected");
}
/* ---------- 通过 js 获取职位列表按钮 ----------- */
function getPositionButtonsViaJs(update_id, v)
{
	var up_block = $(update_id);
	var a;
	up_block.html("");
	if (typeof(__company_2_position__) != 'undefined')
	{
		$.each(__company_2_position__, function(i, n) {
			if (typeof(__company_2_position__[i][0][v]) != 'undefined') { a = __company_2_position__[i][0][v]; }
		});
	}
	if (typeof(a) != 'undefined')
	{
		$.each(a[0], function(i, n) {
			up_block.append($("<input type=\"button\" />").attr("pid", i).attr("power", n[1]).val(n[0]));
		});
	}
}





/* -------- 通过 js 获取公司列表 --------- */
function getCompanyListViaJsShort(update_id, selected)
{
	var up_block = $(update_id);
	up_block.html("").append($("<option></option>").val("-1").html("请选择公司..."));
	if (typeof(__company_user__) != 'undefined')
	{
		$.each(__company_user__, function(i, n) {
			up_block.append($("<option></option>").val(i).attr("power", n[2]).html(n[1]));
		});
	}
	up_block.find("option[@value='" + selected + "']").attr("selected", "selected");
}
/* 通过 js 由公司获取用户列表 */
function getUserListViaJsShort(update_id, v, selected, except)
{
   var up_block = $(update_id);
   up_block.html("").append($("<option></option>").val("-1").html("请选择人员..."));
   $.each(__company_user__[v][0], function(i, n) {
   		if (n[0] != except)
   		{
   			up_block.append($("<option></option>").val(n[0]).html(n[1]));
   		}
   });
   up_block.find("option[@value='" + selected + "']").attr("selected", "selected");
}






/* 取得公文状态小块 */
function getDocStatusBlock(flag, tip)
{
	var str = {
		0: ["多人审批", "单人审批"],
		1: ["已发送", "已保存，未发送"],
		2: ["已取消", "正常状态"],
		3: ["审批已结束", "正在流转中"],
		4: ["审批已通过", "未通过审批"]
	};
	switch (flag)
	{
		case "1":
			return "<a class=\"doc_status_tip1\" href=\"#\" onclick=\"return false;\" linktitle=\"" + str[tip][0] + "\">1</a>";
			break;
		default:
			return "<a class=\"doc_status_tip0\" href=\"#\" onclick=\"return false;\" linktitle=\"" + str[tip][1] + "\">0</a>";
	}
}

// 初始化 AJAX 动作
function initBlockUI()
{
	var pmc = {
		border: 0,
		padding: "15px",
		backgroundColor: 'black',
		'-webkit-border-radius': '10px', 
        '-moz-border-radius': '10px', 
        opacity: '0.5',
        color: 'white'
	};
	$.blockUI.defaults.pageMessage = "<div class=\"ajaxloading\"><img src=\"../images/ajax.gif\" /> &nbsp; 数据载入中，请稍候...</div>";
	// $.blockUI.defaults.overlayCSS = { backgroundColor: 'white', opacity: '0.5' };
	$.blockUI.defaults.overlayCSS = { backgroundColor: 'transparent' };
	$.each(pmc, function(i, n) {
		$.blockUI.defaults.pageMessageCSS[i] = n;
	});
	$().ajaxStart($.blockUI).ajaxStop($.unblockUI);
}

// 从一个数组的值中删减另一个数组的值，返回结果数组
function arrayDeleteFromAnother(full, cutter)
{
	var temp = [];
	$.each(full, function(i, n){
		var flag = false;
		for (var j=0; j < cutter.length; j ++)
		{
			if (n == cutter[j]) { flag = true; break; }
		}
		if (flag == false) { temp[temp.length] = n; }
	});
	return temp;
}

// 合并两个数组，并去除相同的值
function arrayMergeUnique(a1, a2)
{
	var temp = a1.slice(0);
	return arrayUnique(temp.concat(a2));
}

// 去除数组中相同的值
function arrayUnique(a)
{
	var temp = [];
	$.each(a, function(i, n) {
		var flag = false;
		for (var j = 0; j < temp.length; j ++)
		{
			if (n == temp[j]) { flag = true; break; }
		}
		if (flag == false) { temp[temp.length] = n; }
	});
	return temp;
}

// 生成权限选择框
// full 为备选的权限值数组，selected 为已选择的权限数组，blockid 为返回块的 id 号，name 为复选框的名称
function makePowerCheckBox(full, selected, blockid, name)
{
	var checkdiv = $("<div></div>").attr({id: blockid, name: blockid});
	$.each(full, function(i, n){
		var flag = false;
		for (var j = 0; j < selected.length; j ++) { if (n == selected[j]) { flag = true; break; } }
		if (typeof(__powerArray__[n]) != 'undefined')
		{
			var power_name = __powerArray__[n][2];
			var checked = flag ? " checked=\"checked\" " : "";
			$("<span></span>").append($("<input type=\"checkbox\" " + checked + " />").attr("name", name).val(n))
				.append(power_name).appendTo(checkdiv);
		}
	});
	return checkdiv;
}

// 列出权限列表
function getPowerListViaJs(a)
{
	var listul = $("<ul></ul>");
	if (typeof(a) != 'undefined')
	{
		$.each(a, function(i, n) {
			if (typeof(__powerArray__[n]) != 'undefined')
			{
				var power_name = __powerArray__[n][2];
				$("<li></li>").html(power_name).appendTo(listul);
			}
		});
	}
	return listul;
}

// modal 的关/启
function modalShowClose(block, flag)
{
	if (flag) { $(block).css("visibility", "hidden"); }
	else { $(block).css("visibility", "visible"); $.modal.close(); }
}

/* 分析表单类型模板的各项表单数据，返回处理后的表单代码 */
function getTplInput(name, type, sizeX, sizeY, options)
{
   var str = "";
   var width = (sizeX > 0) ? "width:" + sizeX + "px;" : "";
   var height = (sizeY > 0) ? "height:" + sizeY + "px;" : "";
   var style_X = " style=\"" + width + "\" ";
   var style_XY = " style=\"" + width + height + "\" ";
   var idname = " id=\"" + name + "\" name=\"" + name + "\"";
   switch (type)
	 {
	  case "t":
		str += "<input type=\"text\" " + idname + style_X + " value=\"" + options + "\" />";
		break;
	  case "l":
		str += "<input type=\"text\" " + idname + style_X + " value=\"" + options + "\" disabled=\"disabled\"/>";
		break;
	  case "a":
		str += "<textarea " + idname + style_XY + ">" + options + "</textarea>";
		break;
	  case "r":
		var names = " name=\"" + name + "[]\" ";
		var opt_items = options.split("|");
		for (var i = 0; i < opt_items.length; i ++)
		  {
			 var checked = (i == 0) ? " checked=\"checked\" " : "";
			 str += "<input type=\"radio\" id=\"" + name + "_" + i + "\" " + names + " value=\"" + opt_items[i] + "\" " + checked + " /> " + opt_items[i] + " ";
		  }
		break;
	  case "c":
		var names = " name=\"" + name + "[]\" ";
		var opt_items = options.split("|");
		for (var i = 0; i < opt_items.length; i ++)
		  {
			 str += "<input type=\"checkbox\" id=\"" + name + "_" + i + "\" " + names + " value=\"" + opt_items[i] + "\" /> " + opt_items[i] + " ";
		  }
		break;
	  case "p":
		str += "<input type=\"password\" " + idname + style_X + " value=\"" + options + "\" />";
		break;
	  case "s":
		var opt_items = options.split("|");
		str += "<select " + idname + style_X + ">";
		for (var i = 0; i < opt_items.length; i ++)
		  {
			 var selected = (i == 0) ? " selected=\"selected\" " : "";
			 str += "<option value=\"" + opt_items[i] + "\" " + selected + "> " + opt_items[i] + "</option>";
		  }
		str += "</select>";
		break;
	  default:
		str = "";
		break;
	 }
   return str;
}

/* 分析表单类型模板的各项表单数据，返回处理后的表单代码 */
function getTplInput2(name, type, css, ha)
{
	var h = { content: "", options: {} };
	$.each(ha, function(i, n) {
		h[i] = n;
	});
	switch (type)
	{
		case "no":
			return "";
			break;
		case "t":
			return $("<input type=\"text\" />").val(h["content"]).css(css).attr("id", "_formfill_" + name).attr("name", "_formfill_" + name);
			break;
		case "l":
			return $("<input type=\"text\" disabled=\"disabled\" />").val(h["content"]).css(css).attr("id", "_formfill_" + name).attr("name", "_formfill_" + name);
			break;
		case "a":
			return $("<textarea></textarea>").val(h["content"]).css(css).attr("id", "_formfill_" + name).attr("name", "_formfill_" + name);
			break;
		case "r":
			var temp = $("<span></span>");
			var flag = 0;
			$.each(h["options"], function(i, n) {
				var checked = (flag == 0) ? " checked=\"checked\" " : "";
				temp.append($("<input type=\"radio\" name=\"_formfill_" + name + "\" " + checked + " />").val(i))
					.append(n + " ");
				flag ++;
			});
			return temp;
			break;
		case "c":
			var temp = $("<span></span>");
			$.each(h["options"], function(i, n) {
				temp.append($("<input type=\"checkbox\" name=\"_formfill_" + name + "\" />").val(i))
					.append(n + " ");
			});
			return temp;
			break;
		case "p":
			return $("<input type=\"password\" />").val(h["content"]).css(css).attr("id", "_formfill_" + name).attr("name", "_formfill_" + name);
			break;
		case "s":
			var temp = $("<select></select>").css(css).attr("id", "_formfill_" + name).attr("name", "_formfill_" + name);
			$.each(h["options"], function(i, n) {
				temp.append($("<option></option>").val(i).html(n));
			});
			return temp;
			break;
	}
	// 填写
}

/* -------------  FCKEditor 操作函数  ------------- */
/* 加载 FCKeditor */
function show_FCKEditor(id, size)
{
   if (!size["width"]) { size["width"] = "100%"; }
   if (!size["height"]) { size["height"] = "200"; }
   var oEditor = new FCKeditor(id);
   oEditor.BasePath = "../fckeditor/";
   // oEditor.BasePath = "/oa/www/fckeditor/";
   oEditor.Width = size["width"];
   oEditor.Height = size["height"];
   oEditor.ReplaceTextarea();
}

/* 获取 FCKeditor 数据 */
function get_FCKData(id)
{
   var  oEditor = FCKeditorAPI.GetInstance(id);
   return oEditor.GetXHTML(true);
}

/* 设置 FCKeditor 数据 */
function set_FCKData(EditorName, ContentStr) {
      var oEditor = FCKeditorAPI.GetInstance(EditorName) ;
      oEditor.SetHTML(ContentStr) ;
}

/* -------------- 数组操作 -------------- */
/* 检测数组中是否有相同的元素 */
/* 传入一个数组，如果有相同元素，则返回相同元素，如没有，则返回 false */
function checkArraySame(a)
{
   if (!a) { return false; }
   // 复制一份给新的数组，不然会修改原数组，因为 javascript 操作对象是引用方式
   // slice(start, end) 是截取函数，截取从 start 到 end 的元素到新数组中，
   // 省略 end 则表示截取到结尾
   var l = a.slice(0);
   l = l.sort();
   var temp;
   for (var i = 0; i < l.length; i ++)
     {
		if (temp != l[i]) temp = l[i];
		else return temp;
     }
   
   return false;
}

/* 数组到 Hash */
function array2hash(a)
{
   var h = {};
   for (var i = 0; i < a.length; i ++)
     {
		h["" + i] = a[i];
     }
   return h;
}

/* hash 到数组 */
function hash2array(h)
{
	var a = [];
	$.each(h, function(i, n) {
		a[a.length] = n;
	});
	return a;
}



/* --------------- 数据 --------------- */
/* 预设的数据列表 */
var oa_predefine_data = {
	year: { name: "年份",
			fun: function()
			{
				var h = {};
				var date = new Date();
				for (var i = 1950; i <= (date.getFullYear() + 20); i ++ ) { h[i] = i; }
				return h;
			}
	},
	month: { name: "月份",
			fun: function()
			{
				var h = {};
				for (var i = 1; i <= 12; i ++) { h[i] = i; }
				return h;
			}
	},
	date: { name: "日期",
			fun: function()
			{
				var h = {};
				for (var i = 1; i <= 31; i ++) { h[i] = i; }
				return h;
			}
	},
	sex: { name: "性别", fun: function() { return { "男": "男", "女": "女", "保密": "保密" }; } },
	culture: { name: "文化程度", fun: function() {
				return { "博士生": "博士生", "研究生": "研究生", "大学本科": "大学本科", "大学专科": "大学专科",
						"高中": "高中", "中专": "中专", "初中": "初中", "小学": "小学", "其它": "其它"
				}; }
	},
	marriage: { name: "婚姻状况", fun: function() { return { "未婚": "未婚", "已婚": "已婚", "保密": "保密" }; } },
	census_class: { name: "户籍类型", fun: function() { return { "城市": "城市", "农村": "农村", "其它": "其它" }; } }
};

// 获取 URL 参数方法
function $G(){
	var Url=window.location.href;//如果想获取框架顶部的url可以用 top.window.location.href
	var u,g,StrBack='';
	if(arguments[arguments.length-1]=="#")
		u=Url.split("#");
	else
		u=Url.split("?");
	if (u.length==1) g='';
	else g=u[1];

	if(g!=''){
		gg=g.split("&");
		var MaxI=gg.length;
		str = arguments[0]+"=";
		for(xm=0;xm<MaxI;xm++){
			if(gg[xm].indexOf(str)==0) {
				StrBack=gg[xm].replace(str,"");
				break;
			}
		}
	}
	return StrBack;
}
